package com.zkingsoft.common.authority.strategy;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.matrix.core.constance.SystemErrorCode;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.tools.EncrypUtil;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.common.service.SysUsersService;

/**
 * 通过认证中心登录
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年12月9日
 */
public class SsoAccountPwdLoginStrategy implements LoginStrategy {

	private SysUsersService sysUsersService;

	private SysUsers user;

	public SsoAccountPwdLoginStrategy(SysUsers user, SysUsersService sysUsersService) {
		this.user = user;
		this.sysUsersService = sysUsersService;
	}

	@Override
	public Object login() {

		// 是否同时有账号和密码
		if (StringUtils.isBlank(user.getSuAccount()) || StringUtils.isBlank(user.getSuPassword())) {
			throw new GlobleException(AppMessageCode.User.ACCOUNT_PASSWORD_MUST_REQUEST);
		}
		// 根据账号查询用户
		SysUsers userQuery = new SysUsers();
		userQuery.setSuAccount(user.getSuAccount());
		List<SysUsers> users = sysUsersService.findByModel(userQuery);
		if (users.size() != 1) {
			LogUtil.error("{}账号不唯一，登录失败", null, user.getSuAccount());
			throw new GlobleException(SystemErrorCode.SYSTEM_RUNNING_ERROR);
		}
		userQuery = users.get(0);
		String pwdSource = user.getSuPassword() + userQuery.getSuRegisterTime().getTime();
		try {
			if (!userQuery.getSuPassword().equals(EncrypUtil.getSha1(pwdSource))) {
				// 账号密码错误
				throw new GlobleException(AppMessageCode.User.ACCOUNT_PASSWORD_ERROR);
			}
		} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
			LogUtil.error("密码加密方法出错", e, user.getSuAccount());
			throw new GlobleException(SystemErrorCode.SYSTEM_RUNNING_ERROR);
		}
		// 后台已经删除账号
		if (userQuery.getSuValid().equals(AppConstance.RECORD_INVALID)) {
			throw new GlobleException(AppMessageCode.User.ACCOUNT_IS_DELETED);
		}

		if (StringUtils.isBlank(userQuery.getSuAccountStatus())) {
			LogUtil.info("用户状态为空登录失败");
			throw new GlobleException(AppMessageCode.User.ACCOUNT_NOT_ACTIVE);
		}

		// 判断用户的状态
		switch (userQuery.getSuAccountStatus()) {

		case AppConstance.ACCOUNT_STATUS_INACTIVATED:
			throw new GlobleException(AppMessageCode.User.ACCOUNT_NOT_ACTIVE);
		case AppConstance.ACCOUNT_STATUS_LOCKED:
			throw new GlobleException(AppMessageCode.User.ACCOUNT_IS_LOCK);
		default:
			// 登录成功
			return userQuery;
		}

	}

}
